package com.kinglumi.ailighting.auth.login.account;

import com.kinglumi.ailighting.auth.login.CustomAuthenticationFailureHandler;
import com.kinglumi.ailighting.auth.login.CustomAuthenticationSuccessHandler;
import com.kinglumi.ailighting.auth.service.auth.impl.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * @author Lxin
 * @version 1.0
 * @date 2021/8/13 14:37
 */
@Component
public class AccountAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Autowired
    private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
    @Autowired
    private CustomAuthenticationFailureHandler customAuthenticationFailureHandler;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        AccountAuthenticationFilter accountAuthenticationFilter = new AccountAuthenticationFilter();
        accountAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        accountAuthenticationFilter.setAuthenticationSuccessHandler(customAuthenticationSuccessHandler);
        accountAuthenticationFilter.setAuthenticationFailureHandler(customAuthenticationFailureHandler);

        AccountAuthenticationProvider accountAuthenticationProvider = new AccountAuthenticationProvider();
        accountAuthenticationProvider.setUserDetailsService(userDetailsService);

        http.authenticationProvider(accountAuthenticationProvider)
                .addFilterAfter(accountAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }

}
